const fs = require('fs');
const path = require('path');
const File = require('../models/fileModel');

exports.uploadFile = (req, res) => {
    const file = req.file;
    const targetPath = path.join(__dirname, '../../uploads', file.originalname);

    fs.rename(file.path, targetPath, async err => {
        if (err) {
            return res.sendStatus(500);
        }

        // 将文件信息保存到数据库中
        const newFile = new File({
            filename: file.originalname,
            path: targetPath,
            size: file.size,
        });

        try {
            await newFile.save();
            res.sendStatus(200);
        } catch (err) {
            res.sendStatus(500);
        }
    });
};

exports.getFiles = async (req, res) => {
    try {
        const files = await File.find();
        res.json(files);
    } catch (err) {
        res.sendStatus(500);
    }
};

exports.downloadFile = (req, res) => {
    const filename = req.params.filename;
    const filePath = path.join(__dirname, '../../uploads', filename);
    res.download(filePath);
};